import math

def calc_turn_angle(prev_unique, junction1, junction2):
    pointA = prev_unique.lat, prev_unique.lon
    pointB = junction1.lat, junction1.lon
    pointC = junction2.lat, junction2.lon
    bearing1 = calculate_initial_compass_bearing(pointA, pointB)
    bearing2 = calculate_initial_compass_bearing(pointB, pointC)
    angle = abs(bearing1 - bearing2)
    if angle > 180:
        angle = 360 - angle
    return angle

def calculate_initial_compass_bearing(pointA, pointB):
    """
    https://gist.github.com/jeromer/2005586

    Calculates the bearing between two points.

    The formulae used is the following:

    :Parameters:
      - `pointA: The tuple representing the latitude/longitude for the
        first point. Latitude and longitude must be in decimal degrees
      - `pointB: The tuple representing the latitude/longitude for the
        second point. Latitude and longitude must be in decimal degrees

    :Returns:
      The bearing in degrees

    :Returns Type:
      float
    """
    if (type(pointA) != tuple) or (type(pointB) != tuple):
        raise TypeError("Only tuples are supported as arguments")

    lat1 = math.radians(pointA[0])
    lat2 = math.radians(pointB[0])

    diffLong = math.radians(pointB[1] - pointA[1])

    x = math.sin(diffLong) * math.cos(lat2)
    y = math.cos(lat1) * math.sin(lat2) - (math.sin(lat1)
            * math.cos(lat2) * math.cos(diffLong))

    initial_bearing = math.atan2(x, y)

    # Now we have the initial bearing but math.atan2 return values
    # The solution is to normalize the initial bearing as shown below
    initial_bearing = math.degrees(initial_bearing)
    compass_bearing = (initial_bearing + 360) % 360

    return compass_bearing